// 接口统一以api开头 2018.09.22
// api格式{stateCode:'200',msg:'',data:[]}
// 接收post数据
var formidable = require("formidable");
var md5 = require("../base/md5.js");
var resInfo = require('../base/resInfo')
var ObjectId = require("mongodb").ObjectId
var fs = require('fs')
var path = require('path')


// 引入数据库模型
var user = require('../models/user')
var news = require('../models/news')
var type = require('../models/type')
var project = require('../models/project')

// 登录
exports.login = function(req, res, next) {
    let password = md5.dealPassword(req.query.password)
    user.find({username: req.query.username, password: password}, function(err, result) {
        console.log('result', result)
        if(result.length == 0 ) {
            res.send(resInfo.resInfo('300','账号密码错误'))
        }else {
            req.session.login = "1";
            req.session.username = req.query.username;
            res.send(resInfo.resInfo());
        }
    })
}
// 注册
exports.registered = function(req, res, next) {
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        // res.writeHead(200, {'content-type': 'text/plain'});
        if(err) {
            res.send(resInfo.resInfo('503','服务器错误'))
            res.end()
        }
        user.find({username: fields.username}, function(err, result) {
            if(result.length==0) {
                let userInfo = fields
                userInfo.password = md5.dealPassword(fields.password)
                user.create(userInfo, function(err, info) {
                    if (err) return handleError(err);
                    if(info) {
                        res.send(resInfo.resInfo())
                    }
                })
            }
        })
    });
}

// 新增博客
exports.addNews = function(req, res, next) {
    console.log('addBlog', req.session)

    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        // res.writeHead(200, {'content-type': 'text/plain'});
        if(err) {
            res.send(resInfo.resInfo('503','服务器错误'))
            res.end()
        }
        if(fields._id) {
            let id = ObjectId(fields._id)
            news.update({_id: id}, fields, (err, info) => {
                if(info.n>0) {
                    res.send(resInfo.resInfo())
                }
            })
        }else {
            news.create(fields, function(err, info) {
                if (err) return handleError(err);
                if(info) {
                    res.send(resInfo.resInfo())
                }
            })
        }
    });

}

exports.getNews = function(req, res, next) {
    let search = {}
    req.query.id ? search._id = ObjectId(req.query.id) : ''
    console.log(req.query.title)
    if(req.query.title) {
        search.title = new RegExp(req.query.title)
    }
    if(search._id) {
        let ip = getClientIp(req)
        news.find({_id: search._id}, function(err, info) {
            if(info.length > 0) {
                let obj = info[0].read
                let have = false
                if(obj) {
                    obj.map(item => {
                        if(item == ip) {
                            have = true
                        }
                    })
                }
                if(!have) {
                    obj.push(ip)
                    news.update({_id: search._id}, {$set: {read: obj}},function(err, info) {
                        console.log(info)
                    })
                }
            }
        })
    }
    
    req.query.type ? search.type = req.query.type: ''
    req.query.project ? search.project = req.query.project: ''
    req.query.author ? search.author = req.query.author: ''

    let pageSize = req.query.pageSize? req.query.pageSize: 0
    let page = req.query.page? req.query.page: 0
    let skip = (parseInt(page) - 1) * parseInt(pageSize) || 0
    console.log(search)
    news.find(search)
        .limit(pageSize)
        .skip(skip)
        .sort({'_id':-1})
        .exec(function(err,info) {
            if(err) {
                res.send(resInfo.resInfo('503','服务器错误'))
                res.end()
            }

            if(info.length > 0) {
                res.send(resInfo.resInfo('200','请求成功', info))
            }else {
                res.send(resInfo.resInfo())
            }
        });

}


exports.deleteNews = function(req, res, next) {
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        if(fields.id) {
            let id = ObjectId(fields.id)
            news.remove({_id: id}, (err, info) => {
                if(info.n>0) {
                    res.send(resInfo.resInfo())
                }
            })
        }
    })
}

// 获取专题列表
exports.getProject = function(req, res, next) {
    var obj = {}
    if(req.query._id) {
        console.log('123456', req.query._id)
        obj._id = ObjectId(req.query._id)
    }
    let pageSize = req.query.pageSize? req.query.pageSize: 0
    let page = req.query.page? req.query.page: 0
    let skip = (parseInt(page) - 1) * parseInt(pageSize) || 0
    console.log('obj', obj)
    project.find(obj)
        .limit(pageSize)
        .skip(skip)
        .sort({'_id':-1})
        .exec(function(err,info) {
            if(err) {
                res.send(resInfo.resInfo('503','服务器错误'))
                res.end()
            }

            if(info.length > 0) {
                res.send(resInfo.resInfo('200','请求成功', info))
            }else {
                res.send(resInfo.resInfo())
            }
        });
}

exports.updateProject = function(req, res, next) {
    var form = new formidable.IncomingForm();
    form.uploadDir = "./uploads";
    console.log(req.url)

    form.parse(req, function(err, fields, files) {
        let obj = JSON.parse(fields.data)
        if(obj._id) {
            if(files.file.name) {
                var extname = path.extname(files.file.name)
                //旧的路径
                var oldpath =path.join(__dirname, '..' ) + "/" + files.file.path
                //新的路径
                var newpath = path.join(__dirname, '..' )+ '/uploads/'+ obj.name + extname
                let imgPath = '/'+ obj.name +extname
                fs.rename(oldpath,newpath,function (err) {
                    if(err){
                        throw  Error("文件上传失败");
                    }
                    obj.img = imgPath
                    let id = ObjectId(obj._id)
                    project.update({_id: id}, obj, (err, info) => {
                        if(info.n>0) {
                            return res.send(resInfo.resInfo())
                        }
                    })
                });
            }else {
                let id = ObjectId(obj._id)
                project.update({_id: id}, obj, (err, info) => {
                    if(info.n>0) {
                        return res.send(resInfo.resInfo())
                    }
                })
            }
        }else {
            var extname = path.extname(files.file.name)
            //旧的路径
            var oldpath =path.join(__dirname, '..' ) + "/" + files.file.path
            //新的路径
            var newpath = path.join(__dirname, '..' )+ '/uploads/'+ obj.name + extname
            fs.rename(oldpath,newpath,function (err) {
                if(err){
                    throw  Error("文件上传失败");
                }
                let imgPath = '/'+ obj.name +extname
                project.create({
                    name: obj.name,
                    introduction: obj.introduction,
                    'img': imgPath
                }, (err, info)=> {
                    return res.send(resInfo.resInfo())
                })
            });
        }
    })
}

exports.removeProject = function(req, res, next) {
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        if(fields.id) {
            let id = ObjectId(fields.id)
            project.remove({_id: id}, (err, info) => {
                if(info.n>0) {
                    res.send(resInfo.resInfo())
                }
            })
        }
    })
}

// 
exports.getType = function(req, res, next) {
    let pageSize = req.query.pageSize? req.query.pageSize: 0
    let page = req.query.page? req.query.page: 0
    let skip = (parseInt(page) - 1) * parseInt(pageSize) || 0
    type.find()
        .limit(pageSize)
        .skip(skip)
        .sort({'_id':-1})
        .exec(function(err,info) {
            if(err) {
                res.send(resInfo.resInfo('503','服务器错误'))
                res.end()
            }

            if(info.length > 0) {
                res.send(resInfo.resInfo('200','请求成功', info))
            }else {
                res.send(resInfo.resInfo())
            }
        });
}

exports.updateType = function(req, res, next) {
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        if(fields.id) {
            let id = ObjectId(fields.id)
            type.update({_id: id},fields, (err, info) => {
                if(info.n>0) {
                    res.send(resInfo.resInfo())
                }
            })
        }else {
            type.create(fields, (err, info)=> {
                res.send(resInfo.resInfo())
            })
        }
    })
}

exports.removeType = function(req, res, next) {
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        if(fields.id) {
            let id = ObjectId(fields.id)
            type.remove({_id: id}, (err, info) => {
                if(info.n>0) {
                    res.send(resInfo.resInfo())
                }
            })
        }
    })
}

function getClientIp (req) {
    var ip = req.headers['x-real-ip'] ||
    req.headers['x-forwarded-for'] || 
    req.socket.remoteAddress || ''; 
    if(ip.split(',').length>0){
        ip = ip.split(',')[0];    
    }    
    return ip;
}
